#include <STC15F2K60S2.H>
#include <stdio.H>
#include <time.H>
#include <Seg.H>
#include <key.H>
#include <LED.H>
#include <uart.H>
#include <ultra.H>
#include <sys.H>
#include <iic.H>
#include <ds1302.H>
#include <onewrie.H>

unsigned int Proc_SlowDowm;
unsigned char Proc_Flag;

unsigned char Key_Val,Key_Down,Key_Up,Key_Old;
unsigned char Seg_Pos;
unsigned char Seg_DulaScan[]={10,10,10,10,10,10,10,10};
unsigned char Seg_PointScan[]={0,0,0,0,0,0,0,0};

unsigned char LED_Enable[]={0,0,0,0,0,0,0,0};

unsigned char Uart_Index;
unsigned char Uart_Rec[10];
unsigned char Ultra_Dat;
float Temperature_Dat;
float Vlotage_Dat;
unsigned char Time_Clock[]={11,11,11};
void Key_Proc()
{
	if(Proc_Flag!=1)return;
		Proc_Flag=0;
	
	Key_Val=Key_Read();
	Key_Down=Key_Val&(Key_Old^Key_Val);
	Key_Up=~Key_Val&(Key_Old^Key_Val);
	Key_Old=Key_Val;
	switch(Key_Down)
	{
		case 16:
			printf("Love you Cheng\r\n");
		break;
	}
}

void Read_Proc()
{
	switch(Proc_Flag)
	{
		case 4:
			Ultra_Dat=Ultra_Wave_Dat();
			Temperature_Dat=Temperature_Read();
			Vlotage_Dat=Vlotage_ReadAD(0x03)/51.0;
			Proc_Flag=0;
		break;
	}
}
void Seg_Proc()
{
	if(Proc_Flag!=2)return;
		Proc_Flag=0;
	Seg_PointScan[6]=1;
	Seg_DulaScan[6]=(unsigned char)(Vlotage_Dat*10)/10%10;
	Seg_DulaScan[7]=(unsigned char)(Vlotage_Dat*10)%10;
	
//	Seg_PointScan[6]=1;
//	Seg_DulaScan[5]=(unsigned int)(Temperature_Dat*10)/100%10;
//	Seg_DulaScan[6]=(unsigned int)(Temperature_Dat*10)/10%10;
//	Seg_DulaScan[7]=(unsigned int)(Temperature_Dat*10)%10;
}

void LED_Proc()
{
	LED_Enable[0]=1;
	LED_Enable[1]=1;
	LED_Enable[2]=1;
}

void Uart_Proc()
{
	if(Proc_Flag!=3)return;
		Proc_Flag=0;
	
	if(Uart_Index>0 && Uart_Index==6)
	{
		if(Uart_Rec[0]=='s'&&Uart_Rec[1]==':'
			&&Uart_Rec[4]=='\r'&&Uart_Rec[5]=='\n')
		{
			Time_Clock[0]=(Uart_Rec[2]-'0')*10+Uart_Rec[3]-'0';
			DS1302_SetTime(Time_Clock);
		}
			
	}
}

void Timer1Service() interrupt 3
{
	if(++Proc_SlowDowm==500)Proc_SlowDowm=0;
	
	if(Proc_SlowDowm%9==0)Proc_Flag=1;
	if(Proc_SlowDowm%50==0)Proc_Flag=2;
	if(Proc_SlowDowm%100==0)Proc_Flag=3;
	if(Proc_SlowDowm%200==0)Proc_Flag=4;
	
	if(++Seg_Pos==8)Seg_Pos=0;
	Seg_DisPlay(Seg_Pos,Seg_DulaScan[Seg_Pos],Seg_PointScan[Seg_Pos]);
	LED_DisPlay(Seg_Pos,LED_Enable[Seg_Pos]);
}

void UartService() interrupt 4
{
	if(RI==1 && Uart_Index<8)
	{
		Uart_Rec[Uart_Index]=SBUF;
		Uart_Index++;
		RI=0;
	}
	if(Uart_Index>7)Uart_Index=0;
}

void main()
{
	Sys_Init();
	Timer1Init();
	UartInit();
	DS1302_SetTime(Time_Clock);
	while(1)
	{
		Key_Proc();
		Read_Proc();
		Seg_Proc();
		LED_Proc();
		Uart_Proc();
	}
}
